﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace Mind.Data
{

    public class DataAccessScope : IDisposable
    {
        private static Dictionary<Thread, Stack<DataAccessScope>> _ScopeMap;
        private static Dictionary<DataAccessScope, Thread> _ThreadMap;

        public DataAccess DataAccess { get; private set; }

        public DataAccessScope(DataAccess dataAccess)
        {
            this.DataAccess = dataAccess;
            if (_ScopeMap == null)
                _ScopeMap = new Dictionary<Thread, Stack<DataAccessScope>>();

            if (_ThreadMap == null)
                _ThreadMap = new Dictionary<DataAccessScope, Thread>();


            if (!_ScopeMap.ContainsKey(Thread.CurrentThread))
                _ScopeMap.Add(Thread.CurrentThread, new Stack<DataAccessScope>());

            _ScopeMap[Thread.CurrentThread].Push(this);
            _ThreadMap[this] = Thread.CurrentThread;
        }

        internal static DataAccessScope Current
        {
            get
            {
                if (_ScopeMap == null || !_ScopeMap.ContainsKey(Thread.CurrentThread)) return null;
                return _ScopeMap[Thread.CurrentThread].Peek();
            }
        }

        public void Dispose()
        {
            Thread thread = _ThreadMap[this];
            Stack<DataAccessScope> stack = _ScopeMap[thread];
            if (thread.IsAlive)
                stack.Pop();
            else
            {
                stack.Clear();
                _ScopeMap.Remove(thread);
            }
        }

    }
}